package cn.dzhang.rcp.hyperbola.model;

import java.util.ArrayList;
import java.util.List;

public class ContactGroup extends Contact {
	private List<Contact> entries;
	private List<ContactListener> listeners;

	public ContactGroup(ContactGroup parent, String name) {
		super(parent, name);
		entries = new ArrayList<Contact>();
		listeners = new ArrayList<ContactListener>();
	}

	public void addEntry(Contact entry) {
		if (null == entry || entries.contains(entry)) {
			return;
		}

		entries.add(entry);
		fireContactChanged(entry);
	}

	public void removeEntry(Contact entry) {
		if (entries.contains(entry)) {
			entries.remove(entry);
			fireContactChanged(entry);
		}
	}

	public void addContactListener(ContactListener listener) {
		if (null == listener || listeners.contains(listener)) {
			return;
		}

		listeners.add(listener);
		for (Contact c : entries) {
			if (c instanceof ContactGroup) {
				ContactGroup n = (ContactGroup) c;
				n.addContactListener(listener);
			}

		}
	}

	public void removeContactListener(ContactListener listener) {
		if (listeners.contains(listener)) {
			listeners.remove(listener);

			for (Contact c : entries) {
				if (c instanceof ContactGroup) {
					ContactGroup n = (ContactGroup) c;
					n.removeContactListener(listener);
				}

			}
		}
	}

	private void fireContactChanged(Contact entry) {
		for (ContactListener l : listeners) {
			l.contactChanged(this, entry);
		}
	}

	public List<Contact> getEntries() {
		return entries;
	}
}
